<template>
  <view class="login-container">
    <!-- 用户图标 -->
    <uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
    <!-- 登录按钮 -->
    <button type="primary" @click="getUserInfo" class="btn-login">一键登录</button>
    <!-- 登录提示 -->
    <view class="tip-text">
      登录后尽享权益
    </view>
  </view>
</template>
<script>
  import {
    mapMutations,
    mapState
  } from "vuex";
  export default {
    computed: {
      ...mapState("m_user", ["redirectInfo"])
    },
    methods: {
      ...mapMutations("m_user", ["updateUserInfo", "updateToken", "updateRedirectInfo"]),

      // 获取用户信息
      getUserInfo(e) {
        uni.getUserProfile({
          desc: "获取您的微信头像和昵称",
          success: (res) => {
            this.updateUserInfo(res.userInfo)
            this.getToken(res);
          },
          fail: () => {
            return uni.$showMsg("您取消了授权")
          }
        });
      },

      // 获取用户 Token 
      async getToken(info) {
        const [err, res] = await uni.login().catch(err => err)
        if (err || res.errMsg !== "login:ok") return uni.$showMsg("登录失败！");
        // 请求参数
        const query = {
          code: res.code,
          encryptedData: info.encryptedData,
          iv: info.iv,
          rawData: info.rawData,
          signature: info.signature
        };
        // 调用登录接口获取 token 
        const {
          data: loginResult
        } = await uni.$http.post("/api/public/v1/users/wxlogin", query)
        if (loginResult.meta.status !== 200 && false) return uni.$showMsg("登录失败！");
        this.updateToken(
          "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo" ||
          loginResult.message.token
        )
        uni.$showMsg("登录成功！");

        // 重定向到购物车页面
        this.navigationBack()
      },

      // 重定向到购物车页面
      navigationBack() {
        if (this.redirectInfo && this.redirectInfo.openType === "switchTab") {
          uni.switchTab({
            url: this.redirectInfo.from,
            complete: () => {
              this.updateRedirectInfo(null)
            }
          })
        }
      }
    }
  }
</script>
<style lang="scss">
  .login-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 750rpx;
    justify-content: center;
    position: relative;
    overflow: hidden;
    background-color: #F8F8F8;

    &::after {
      content: " ";
      display: block;
      width: 100%;
      height: 40px;
      background-color: #FFF;
      position: absolute;
      bottom: 0;
      left: 0;
      border-radius: 100%;
      transform: translateY(50%);
    }

    .btn-login {
      width: 90%;
      border-radius: 100px;
      background-color: #C00000;
      margin: 15px 0;
    }

    .tip-text {
      font-size: 12px;
      color: gray;
    }
  }
</style>